package com.jiyongjun.component.core.model;

import com.alibaba.fastjson.JSON;
import com.jiyongjun.component.core.annotation.JsonObject;
import com.jiyongjun.component.enums.LogApiTypeEnum;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;

import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static com.jiyongjun.component.enums.LogConstant.LOG_EXCEPTION_KEYWORD;

/**
 * <h2></h2>
 * <h3>描述：</h3>
 *
 * @author yongjun.jyj
 * @since 2022/7/14 19:20
 */
@Getter
@Slf4j
@Accessors(chain = true)
public class MqLogContext extends BaseLogContext<MqLogContext>{

    /** topic */
    private String topic;
    @Setter
    private String expression;

    private String tag;
    @JsonObject
    private MessageInner message;

    /** 是否是发送消息 */
    @Setter
    private String type;

    public static final MqLogContext NO_OP_CONTEXT = new MqLogContext(null, null);
    /**
     * @param apiUniqueName 接口名
     * @param logThreadLocal 日志上下文
     */
    protected MqLogContext(String apiUniqueName, ThreadLocal<Map<String, BaseLogContext<?>>> logThreadLocal) {
        super(apiUniqueName, logThreadLocal);
        this.apiType = LogApiTypeEnum.MQ.getCode();
    }

    public @NotNull static MqLogContext getLogContext(String apiName) {
        try {
            return (MqLogContext) LogContext.getLogContext(MqLogContext.class, apiName, true);
        } catch (Exception e) {
            log.warn("{}|获取method日志上下文异常|apiName={},msg={}", LOG_EXCEPTION_KEYWORD, apiName, e.getMessage(), e);
            return NO_OP_CONTEXT;
        }
    }

    public MqLogContext setMessage(Message message) {
        this.topic = message.getTopic();
        this.tag = message.getTags();
        this.message = MessageInner.from(message);

        return this;
    }

    @Data
    @Accessors(chain = true)
    private static class MessageInner {
        private String msgId;
        private String key;
        private String tag;
        private String topic;
        private Object body;

        public static MessageInner from(Message message) {
            MessageInner messageInner = new MessageInner();
            messageInner.setMsgId(message.getBuyerId());
            messageInner.setKey(message.getKeys());
            messageInner.setTag(message.getTags());
            messageInner.setTopic(message.getTopic());

            try {
                messageInner.setBody(JSON.parseObject(new String(message.getBody(), StandardCharsets.UTF_8)));
            } catch (Exception e) {
                log.error("{}|解析消息体异常|msg={}", LOG_EXCEPTION_KEYWORD, e.getMessage(), e);
            }
            return messageInner;
        }
    }

}
